package com.fixme4trade.business;

import java.util.List;

import javax.inject.Inject;

import org.slf4j.Logger;

import com.fixme4trade.persistence.SellDAO;
import com.fixme4trade.constant.PaymentStatus;
import com.fixme4trade.domain.Customer;
import com.fixme4trade.domain.Payment;
import com.fixme4trade.domain.Product;
import com.fixme4trade.domain.Sell;
import com.fixme4trade.domain.Seller;

import br.gov.frameworkdemoiselle.message.MessageContext;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.frameworkdemoiselle.template.DelegateCrud;
import br.gov.frameworkdemoiselle.transaction.Transactional;

@BusinessController
public class SellBC extends DelegateCrud<Sell, Long, SellDAO> {
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private Logger logger;
	
	@Inject
    private MessageContext messageContext;
	
	@Inject
	private ProductBC productBC;
	
	@Inject
	private UserBC userBC;
	
	//@Inject
	//private CustomerBC customerBC;
	
	//@Inject
	//private SellerBC sellerBC;	
	
	@Override
	public void insert(Sell s) {
		super.insert(s);
	}

	@Override
	public void update(Sell s) {
		super.update(s);
	}

	@Override
	public void delete(Long id) {
		super.delete(id);
	}
	
	@Transactional
	public void sellProduct (Product product, Customer customer, int quantity) {
		if (quantity <= product.getQuantity()) {
			Sell sell = new Sell();
			sell.setCustomer(customer);
			sell.setProduct(product);			
			sell.setSellTime(new java.util.Date());
			sell.setQuantity(quantity);
			sell.setUnitPrice(product.getPrice());
									
			//customer.getPurchases().add(sell);		
			//product.getOwner().getSales().add(sell);
			
			// !erro de regra de negocio!!! (o decremento deve ser feito somente apos o pagamento)!
			product.setQuantity(product.getQuantity() - quantity);
				
			this.insert(sell);
			productBC.update(product);
			
		} else { 
			//error message!
		}		
	}
	
	public List<Sell> getShoppingCart() throws Exception {
		Customer customer = userBC.getAuthenticatedCustomer();
		if (customer != null)
			return this.getDelegate().getShoppingCart(customer);
		else throw new Exception () {};
	}	
}
